package com.ylb.rent.util;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @AUTHOR:游李滨
 * @DATE:2023/7/4 15:54
 */
@Component
public class EsUtil{


    @Autowired
    ElasticsearchRestTemplate es;

    public <T> List<T> keywordSearch(String field,String keyword,Class<T> c){

        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                //查询条件
                .withQuery(QueryBuilders.matchQuery(field,keyword))
                .build();

        SearchHits<T> search = es.search(nativeSearchQuery,c);
        return search.stream().map(SearchHit::getContent).collect(Collectors.toList());

    }
    public <T> List<T> allSearch(String field,Class<T> c){

        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                //查询条件
                .withQuery(QueryBuilders.matchAllQuery())
                .build();

        SearchHits<T> search = es.search(nativeSearchQuery,c);
        return search.stream().map(SearchHit::getContent).collect(Collectors.toList());

    }


}
